// Copyright (c) 2010 SuccessFactors, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
//     * Redistributions of source code must retain the above
//       copyright notice, this list of conditions and the following
//       disclaimer.
//
//     * Redistributions in binary form must reproduce the above
//       copyright notice, this list of conditions and the following
//       disclaimer in the documentation and/or other materials
//       provided with the distribution.
//
//     * Neither the name of the SuccessFactors, Inc. nor the names of
//       its contributors may be used to endorse or promote products
//       derived from this software without specific prior written
//       permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
// COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
// HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
// STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
// OF THE POSSIBILITY OF SUCH DAMAGE.

package org.owasp.jxt.tag.core;

import java.util.List;
import org.owasp.jxt.Attribute;
import org.owasp.jxt.Encoder;
import org.owasp.jxt.TranslateContext;
import org.owasp.jxt.servlet.JxtServletBase;


/**
 * CorePageNode
 *
 * @author Jeffrey Ichnowski
 * @version $Revision: 8 $
 */
public final class CorePageNode extends AbstractRootNode {

    private static final int DEFAULT_BUFFER_SIZE = 8 * 1024;

    private String _contentType = "text/html;charset=UTF-8";

    private String _errorPageURL;
    private boolean _needsSession = true;
    private int _bufferSize = DEFAULT_BUFFER_SIZE;
    private boolean _autoFlush = true;

    CorePageNode() {
        super("page");
    }

    @Attribute
    public void setContentType(String type) {
        _contentType = type;
    }

    protected void addStandardImports(List<String> imports) {
        imports.add("javax.servlet.*");
        imports.add("javax.servlet.http.*");
        imports.add("javax.servlet.jsp.*");
    }

    @Override
    protected void translateClass(TranslateContext ctx) {
        String className = ctx.getTargetClassName();

        // TODO: add standard imports for JSPs (see non fully-qualified in code below)

        // TODO: track all lastModified times of all files that
        // generated this file.

        String jspFactory = ctx.generateVariableName("JspFactory");

        ctx.codeln("public class "+className+" extends "+
                   JxtServletBase.class.getName()+" {");
        ctx.indent();
        if (true) {

            ctx.codeln("final JspFactory "+jspFactory+" = JspFactory.getDefaultFactory();");
            ctx.codeln();

            // translateSourceFiles(ctx);
            translateDecl(ctx);
            ctx.codeln();

            ctx.codeln("public void _jspService(HttpServletRequest request, HttpServletResponse response)");
            ctx.codeln("    throws java.io.IOException, ServletException {");
            ctx.indent();
            if (true) {
                ctx.codeln("JspWriter out = null;");
                ctx.codeln("final PageContext pageContext = "+jspFactory+
                           ".getPageContext(this, request, response, "+
                           _errorPageURL+", "+_needsSession+", "+_bufferSize+", "+_autoFlush+");");
                ctx.codeln("try {");
                ctx.indent();
                if (true) {

                    ctx.codeln("final HttpSession session = pageContext.getSession();");
                    ctx.codeln("final ServletContext application = pageContext.getServletContext();");
                    ctx.codeln("final ServletConfig config = pageContext.getServletConfig();");
                    ctx.codeln("out = pageContext.getOut();");
                    ctx.codeln("final Object page = this;");
                    ctx.codeln("response.setContentType(\""+Encoder.JAVA_STRING.apply(_contentType)+"\");");
                    ctx.codeln();
                    translateHeader(ctx);
                    translateChildren(ctx, true);
                }
                ctx.outdent();
                ctx.codeln("} catch (Throwable t) {");
                ctx.indent();
                if (true) {
                    ctx.codeln("if (out != null && out.getBufferSize() != 0) {");
                    ctx.indent();
                    if (true) {
                        ctx.codeln("out.clearBuffer();");
                    }
                    ctx.outdent();
                    ctx.codeln("}");
                    ctx.codeln("pageContext.handlePageException(t);");
                }
                ctx.outdent();
                ctx.codeln("} finally {");
                ctx.indent();
                if (true) {
                    ctx.codeln(jspFactory+".releasePageContext(pageContext);");
                }
                ctx.outdent();
                ctx.codeln("}");
            }
            ctx.outdent();
            ctx.codeln("}");
        }
        ctx.outdent();
        ctx.codeln("}");
    }

    public void pushRuntimeEncoder(TranslateContext ctx, Encoder enc) {
        ctx.codeln("out = pageContext.pushBody("+Encoder.class.getName()+"."+enc+".wrap(out));");
        ctx.codeln("try {");
        ctx.indent();
    }

    public void popRuntimeEncoder(TranslateContext ctx) {
        ctx.outdent();
        ctx.codeln("} finally {");
        ctx.indent();
        ctx.codeln("out = pageContext.popBody();");
        ctx.outdent();
        ctx.codeln("}");
    }

} // CorePageNode
